package com.huitone.gddw.controller.worktable.paramconfigmanage;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.common.excel.CreateExcel;
import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.ServiceCodeDef;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.log.Log;
import com.huitone.gddw.log.LogResult;
import com.huitone.gddw.log.LogType;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.IServiceCodeDefService;
import com.huitone.gddw.service.dto.ServiceCodeDefDTO;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 短信类型管理控制器
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="serviceCodeDef")
public class ServiceCodeDefController extends CommonController {

	private final static Logger LOGGER = Logger.getLogger(ServiceCodeDefController.class);
	
	private final static String STATUS_DEL = "2";
	
	@Autowired
	private IServiceCodeDefService serviceCodeDefService;
	
	/**
	 * 短信类型管理查询
	 * @param page
	 * @param request
	 * @return QueryPage
	 */
	@ResponseBody
	@RequestMapping(value="query")
	public QueryPage<ServiceCodeDefDTO> query(QueryPage<ServiceCodeDef> page, HttpServletRequest request) {
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询短信类型";
		Map<String, Object> params = new HashMap<String, Object>();
		String serviceCode = request.getParameter("serviceCode");
		String serviceName = request.getParameter("serviceName");
		params.put("serviceCode", serviceCode);
		params.put("serviceName", serviceName);
		page.setParams(params);
		QueryPage<ServiceCodeDefDTO> result = null;
		try {
			result = serviceCodeDefService.selectPage(page);
		} catch (Exception e) {
			LOGGER.error("查询短信类型信息出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return result;
	}
	
	/**
	 * 获取所有的短信业务
	 * @return List<ServiceCodeDef>
	 */
	@ResponseBody
	@RequestMapping(value="getAll")
	public List<ServiceCodeDef> getAll() {
		try {
			List<ServiceCodeDef> list = serviceCodeDefService.getAll();
			return list;
		} catch (Exception e) {
			LOGGER.error("获取所有的短信业务信息过程中出现异常：" + e.getMessage(), e);
			return new ArrayList<ServiceCodeDef>();
		}
	}
	
	/**
	 * 根据业务端编码获取短信业务信息
	 * @param svrNode 业务端编码
	 * @return List<ServiceCodeDef>
	 */
	@ResponseBody
	@RequestMapping(value="getBySvrNode")
	public List<ServiceCodeDef> getBySvrNode(String svrNode) {
		try {
			List<ServiceCodeDef> list = serviceCodeDefService.getBySvrNode(svrNode);
			return list;
		} catch (Exception e) {
			LOGGER.error("获取短信业务信息过程中出现异常：" + e.getMessage(), e);
			return null;
		}
	}
	
	/**
	 * 更改短信类型
	 * @param serviceCode 短信类型编码
	 * @param status 更改后状态
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="changeStatus")
	public Message changeStatus(String serviceCode, String status) {
		try {
			updateStatus(serviceCode, status);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更改短信类型状态过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
	/**
	 * 更改短信类型
	 * @param serviceCode 短信类型编码
	 * @param status 更改后状态
	 */
	private void updateStatus(String serviceCode, String status) {
		ServiceCodeDef entity = serviceCodeDefService.selectByPrimaryKey(serviceCode);
		entity.setStatus(status);
		serviceCodeDefService.update(entity);
	}
	
	/**
	 * 修改页面数据准备
	 * @param serviceCode 短信类型编码
	 * @return ServiceCodeDefDTO
	 */
	@ResponseBody
	@RequestMapping(value="toUpdate")
	public ServiceCodeDefDTO toUpdate(String serviceCode) {
		try {
			ServiceCodeDefDTO entity = serviceCodeDefService.toUpdate(serviceCode);
			return entity;
		} catch (Exception e) {
			LOGGER.error("跳转修改页面过程中出现异常：" + e.getMessage(), e);
			return new ServiceCodeDefDTO();
		}
	}
	
	/**
	 * 保存短信信息
	 * @param entity ServiceCodeDef
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="save")
	@Log(logType=LogType.UPDATE, content="添加短信类型")
	public Message save(ServiceCodeDef entity, HttpServletRequest request) {
		if (StringUtils.isBlank(entity.getServiceCode())) {
			return new Message(false, "短信类型编码不能为空！");
		}
		try {
			ServiceCodeDef serviceCodeDef = serviceCodeDefService.selectByPrimaryKey(entity.getServiceCode());
			if (serviceCodeDef != null) {
				return new Message(false, "该短信类型编码已存在，不能重复添加！");
			}
			serviceCodeDefService.saveRecord(entity);
			return new Message(true, "保存成功！");
		} catch (Exception e) {
			LOGGER.error("保存短信类型信息过程中出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
			return new Message(false, "保存失败！");
		}
	}
	
	/**
	 * 更新短信类型
	 * @param entity ServiceCodeDef
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="update")
	public Message update(ServiceCodeDef entity) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]修改短信类型";
		boolean isSuccess = true;
		String msg;
		try {
			ServiceCodeDef serviceCodeDef = serviceCodeDefService.selectByPrimaryKey(entity.getServiceCode());
			serviceCodeDef.setServiceName(entity.getServiceName());
			serviceCodeDef.setStatus(entity.getStatus());
			serviceCodeDef.setDesc(entity.getDesc());
			serviceCodeDef.setAcceptMo(entity.getAcceptMo());
			serviceCodeDefService.updateByPrimaryKey(serviceCodeDef);
			msg = "修改成功！";
		} catch (Exception e) {
			LOGGER.error("修改短信类型过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "修改失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 删除短信类型
	 * @param serviceCode 短信类型编码
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="delete")
	public Message delete(String serviceCode) {
		super.logType = SmLog.LOGTYPE_DELETE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]删除短信类型";
		boolean isSuccess = true;
		String msg;
		try {
			updateStatus(serviceCode, STATUS_DEL);
			msg = "删除成功！";
		} catch (Exception e) {
			LOGGER.error("删除业务端信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "删除失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/out-excel", method=RequestMethod.POST)
	public void outExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "短信类型信息表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		
		List<ServiceCodeDefDTO> list = serviceCodeDefService.getRecord(params);
		if (null == list || 0 == list.size()) {
			list.add(new ServiceCodeDefDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	
	/**
	 * 业务短信发送通道
	 * @param serviceCode 短信类型编码
	 * @param gateLinkIds 通道ID
	 * @return Message
	 */
//	@ResponseBody
//	@RequestMapping(value="updateGateLink")
//	public Message updateGateLink(String serviceCode, String gateLinkIds) {
//		try {
//			serviceCodeDefService.updateGateLink(serviceCode, gateLinkIds);
//			return new Message(true, "操作成功！");
//		} catch (Exception e) {
//			LOGGER.error("设置业务短信发送通道过程中出现异常：" + e.getMessage(), e);
//			return new Message(false, "操作失败！");
//		}
//	}
	
}
